package org.example.backend.demos.web.handler;

import com.alibaba.fastjson2.JSON;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.backend.demos.web.result.Result;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import java.io.IOException;
import java.io.PrintWriter;

public class SuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        response.setStatus(200);

        response.setContentType("application/json;charset=utf-8");

        PrintWriter printWriter = response.getWriter();

        UserDetails userDetails = (UserDetails) authentication.getPrincipal();

        Result<UserDetails> success = Result.success(userDetails);

        String json = JSON.toJSONString(success);

        printWriter.println(json);
    }
}
